<?php

namespace app\models;

use Yii;
use yii\helpers\Html;
/**
 * This is the model class for table "tbl_log".
 *
 * @property integer $id
 * @property integer $time
 * @property string $content
 * @property string $type
 * @property string $ua
 * @property string $ip
 */
class Log extends \yii\db\ActiveRecord {

    /**
     * 登录类型
     */
    const Type_login = 1;

    /**
     * 操作类型
     */
    const Type_caozuo = 2;
    /**
     * 登录失败的操作
    */
    const Type_login_fail=3;
    

    public static $TypeArray=[
        self::Type_caozuo=>'操作',
        self::Type_login=>'登录',
        self::Type_login_fail=>'登录失败'
    ];

    /**
     * 是否记录操作
   */
   public static $isWrite=true;
    
    /**
     * 添加cookie登录记录
     */
    public static function addLoginCookie() {
        
        /////如果本次登录过，直接返回
        $sess = Yii::$app->session;
        
      //  exit('addLoginCookie');
        if (isset($sess['addLoginCookie'])) {
            return;
        }
        $sess['addLoginCookie'] = true;
        $new = new self;
        $new->content = '使用cookie登录';
        $new->type = self::Type_login;
        $new->save();
    }

    /**
     * 使用密码登录
     */
    public static function addLoginPass() {
        
        $sess = Yii::$app->session; 
      /*  var_dump($sess['addLoginCookie']);
        exit('addLoginPass');*/
        if (isset($sess['addLoginCookie'])) {            
            return;
        }
        $sess['addLoginCookie'] = true;
        
        $new = new self;
        $new->content = '使用密码登录';
        $new->type = self::Type_login;
        $new->save();
    }

    /**
     * 更新表单数据
     * $className,更新数据的类
     * $field,    更新的字段
     * $oldVal,   旧的指
     * $newVal,   新的值
     * $re        更新返回状态
     */
    public static function addLogUpBaseForm($className, $field, $oldVal, $newVal, $re) {
      
        if(!self::$isWrite){
            ///return;
            $newVal='你懂得';
            $oldVal='你懂得';
        }
        $new = new self;
        $new->content = '<span class="classname">'.$className . '</span></span>:更新了配置文件,' .
                $new->var_export($field,'field') .
                ':旧的值为:' . $new->var_export($oldVal, 'old') .
                ',新的值为:' . $new->var_export($newVal, 'new') .
                ',更新状态:' . $new->var_export($re);
        $new->type = self::Type_caozuo;
        $new->save();
    }
    
    public function var_export($val,$class=''){
        return '<span class="varexport '.$class.'">'.var_export(Html::encode($val),true).'</span>';
    }

    /**
     * 添加表格修改记录
    */
    public static function addLogBaseViewList($modelObj,$array,$r,$isNew,$primaryKey){
      /*  print_r($array);
        var_dump($r);exit;*/ 
        $tableName=$modelObj->tableName();
        $str='在表('.$tableName.')中';
        if($isNew){
            $str.='新增记录('.$primaryKey.')：';
        }else{
            $str.='更新记录('.$primaryKey.'):';
        }
        $attributeLabels=$modelObj->attributeLabels();
        if($array===[]){
            $str.='无更新字段';
        }
        $new=new self;
        foreach ($array as $key=>$vo) {
            $strKey=$key;
            if(isset($attributeLabels[$key])){
                $strKey=$attributeLabels[$key];
            }            
            $str.='字段：<span class="key">'.$strKey.'('.$key.')</span>,旧值为：<span class="old">'.$new->var_export($vo['old'],'old').'</span>，新值为：<span clas="new">'.
                    $new->var_export($vo['new'],'new').'</span>,更新状态:'.$new->var_export($r).'<br>';
        }
        
        $new->content=$str;
        $new->type=self::Type_caozuo;
        $new->save();
    }

    /**
     * 添加登录失败的记录
    */
   public static function addLoginFail($username,$password){
       $new=new self;
       $new->content='登录失败,用户名：'.Html::encode($username).',密码:'.Html::encode($password);
       $new->type=self::Type_login_fail;
       $new->save();
   }

   /**
    * 检测最近有没有登录失败的,如果有返回true，没有登录失败的记录，返回false
   */
  public static function checkLoginFail(){
      $count=self::find()->where(
              'time > :time AND type = :type',
              [
                  ':time'=>time()-600,
                  ':type'=>self::Type_login_fail
              ]
              )->count();
      if($count==='0'){
          return false;
      }else{
          return true;
      }
  }









  public static function addText($text){
      $new=new self;
      $new->content=$text;
      $new->save();
  }











  public function save($runValidation = true, $attributeNames = null) {
        if ($this->isNewRecord) {
            $this->time = time();
            $this->ip = \app\components\Fun::RemoteIp();
            if (isset($_SERVER['HTTP_USER_AGENT'])) {
                $this->ua = $_SERVER['HTTP_USER_AGENT'];
            }
        }
        return parent::save($runValidation, $attributeNames);
    }

    /**
     * @inheritdoc
     */
    public static function tableName() {
        return 'tbl_log';
    }

    /**
     * @inheritdoc
     */
    public function rules() {
        return [
                // [['time'], 'integer'],
                //  [['content'], 'string'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels() {
        return [
            'id' => 'ID',
            'time' => '时间',
            'content' => '内容',
            'type' => '类型',
            'ip' => 'ip',
            'ua' => 'UA'
        ];
    }

}
